<template>
  <div>
    <x-Table
      :loading="loading"
      :table-data="tableData"
      :options-data="options"
      :pagination="pagination"
      :rule-form="ruleForms"
      @handleAdd="handleAdd"
      @handlePaginationCurrentChange="handlePaginationCurrentChange"
      @handlePaginationSizeChange="handlePaginationSizeChange"
      @handleHeardDel="handleHeardDel"
      @searchForm="searchForm"
      @resetForm="resetForm"

    >
    </x-Table>
    <!--    弹窗区域-->
    <el-dialog
      v-dialog-drag
      :title="alertTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="45%"
    >
      <form-create
        v-model="fapi"
        :rule="rule"
        :option="option"
        :value.sync="formParam"
        @submit="onSubmit"
      >
        <!--        课程分页-->
        <template slot="type-page-select-class" >
          <el-select @change="classChange" @clear="classClear" :remote-method="classFilterMethod" remote filterable
                     v-model="rule[0].value"
                     clearable placeholder="请选择">
            <el-option
              style='width: 260px;text-align: center'
              v-for="item in rule[0]['options']"
              :key="item.id"
              :label="item.title + ' => ' + item.garde"
              :value="item.id">
            </el-option>
            <el-pagination
              @current-change="classCurrentChange"
              small
              layout="prev, pager, next"
              :page-size="20"
              :current-page="pageSizes.classPage.currentPage"
              :total="pageSizes.classPage.total">
            </el-pagination>
          </el-select>
        </template>
        <!--        end-->

        <!--        章节分页-->
        <template slot="type-page-select-chapter">
          <el-select @clear="chapterClear"
                     @change="chapterChange"
                     v-model="rule[1].value"
                     clearable placeholder="请选择">
            <el-option
              style='width: 260px;text-align: center'
              v-for="item in rule[1].options"
              :key="item.id"
              :label="item.title"
              :value="item.id">
            </el-option>
            <el-pagination
              @current-change="chapterCurrentChange"
              small
              layout="prev, pager, next"
              :page-size="20"
              :current-page="pageSizes.chapterPage.currentPage"
              :total="pageSizes.chapterPage.total">
            </el-pagination>
          </el-select>
        </template>
        <!--        end-->

        <!--        学生分页-->
        <template slot="type-page-select-user">
          <el-select
            @clear="userClear"
            v-model="rule[2].value"
            clearable placeholder="请选择"
            :remote-method="userFilterMethod" remote filterable
          >
            <el-option
              style='width: 260px;text-align: center'
              v-for="item in rule[2].options"
              :key="item.id"
              :label="item.name + ' => ' + item.idcard"
              :value="item.id">
            </el-option>
            <el-pagination
              @current-change="userCurrentChange"
              small
              layout="prev, pager, next"
              :page-size="20"
              :current-page="pageSizes.userPage.currentPage"
              :total="pageSizes.userPage.total">
            </el-pagination>
          </el-select>
        </template>
        <!--        end-->
      </form-create>
    </el-dialog>
    <!--    end-->
  </div>
</template>

<script>
let _this;
export default {
  data() {
    return {
      loading: true,
      row: null, //当前选择数据
      ruleForms: {
        // title: {label: "专业名称", prop: "title", type: "text"},
        // code: {label: "专业代码", prop: "major_code", type: "text"},
        // type: {
        //   label: "层次",
        //   prop: "level",
        //   type: "select",
        //   select: [{label: '专科', value: '专科'}, {label: '本科', value: '本科'}]
        // },
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        pageSizes: [10, 20, 50, 100],
      }, //分页参数
      otherParam: {
        halfCheckedKeys: [],
      }, //如果有其他情况会拼接这个参数
      fapi: {},
      formParam: {},
      ruleFormSearch: {//自定义表单搜索内容
        class_id: '',
        chapter_id: '',
        user_id: ''
      },
      pageSizes: {
        classPage: {
          currentPage: 1,
          total: 0,
        },//课程分页参数
        chapterPage: {
          currentPage: 1,
          total: 0,
        },//章节分页参数
        userPage: {
          currentPage: 1,
          total: 0,
        },//学生分页参数
      },
      rule: [
        {
          "type": "pageSelectClass",
          "field": "class_id",
          "title": "课程名称",
          "info": "",
          "options": [],
          "hidden": false,
          "display": true,
          "value": '',
          "validate": [
            {
              "trigger": "change",
              "mode": "required",
              "message": "请选择课程",
              "required": true,
              "type": "number"
            }
          ]
        },
        {
          "type": "pageSelectChapter",
          "field": "chapter_id",
          "title": "章节id",
          "info": "",
          "options": [],
          "hidden": false,
          "display": true,
          "value": '',
          "validate": [
            {
              "trigger": "change",
              "mode": "required",
              "message": "请选择章节",
              "required": true,
              "type": "number"
            }
          ]
        },
        {
          "type": "pageSelectUser",
          "field": "user_id",
          "title": "用户名",
          "info": "",
          "options": [],
          "hidden": false,
          "display": true,
          "value": '',
          "validate": [
            {
              "trigger": "change",
              "mode": "required",
              "message": "请选择学生",
              "required": true,
              "type": "number"
            }
          ]
        },
        {
          "type": "input",
          "field": "chapter_name",
          "title": "章节名称",
          "info": "",
          "_fc_drag_tag": "input",
          "hidden": false,
          "display": true
        },
        {
          "type": "input",
          "field": "play_time",
          "title": "当前播放时间",
          "info": "",
          "_fc_drag_tag": "input",
          "hidden": false,
          "display": true
        },
        {
          "type": "switch",
          "field": "is_pass",
          "title": "是否播放完成",
          "info": "",
          "_fc_drag_tag": "switch",
          "hidden": false,
          "display": true
        }
      ],
      option: {
        form: {
          inline: false,
          labelPosition: "right",
          size: "small",
          labelWidth: "125px",
          hideRequiredAsterisk: false,
          showMessage: true,
          inlineMessage: false,
        },
        resetBtn: true,
      },
      dialogVisible: false,
      alertTitle: "添加",
      tableData: [],
      options: {
        fields: {
          id: {label: "ID", prop: "id", width: "120", order: true},
          class_id: {label: "课程名称", prop: "class_id", type: 'two', options: {obj: 'officeClass', objKey: 'title'}},
          // chapter_id: {label: "章节id", prop: "chapter_id"},
          user_id: {label: "用户名", prop: "user_id", type: 'two', options: {obj: 'users', objKey: 'name'}},
          chapter_name: {label: "章节名称", prop: "chapter_name"},
          play_time: {label: "播放时间", prop: "play_time"},
          is_pass: {
            label: "是否播放完成",
            prop: "is_pass",
            type: "switch",
            activeValue: true,
            inactiveValue: false,
            switchChage: function (scope) {
              console.log(scope)
            },
          },
          create_time: {label: "创建时间", prop: "create_time", order: true},
          button: {
            label: "操作",
            width: "130",
            type: "func",
            fixed: true,
            edit: function (scope) {
              setTimeout(() => {
                _this.fapi.setValue("class_id", scope["row"].class_id);
                _this.fapi.setValue("chapter_id", scope["row"].chapter_id);
                _this.fapi.setValue("user_id", scope["row"]['user_id']);
                _this.fapi.setValue("chapter_name", scope["row"]['chapter_name']);
                _this.fapi.setValue("is_pass", scope["row"]['is_pass']);
                _this.fapi.setValue("play_time", scope["row"]['play_time']);
              }, 0);
              _this.row = scope["row"];
              _this.alertTitle = "编辑";
              _this.dialogVisible = true;
            },
            del: function (scope) {
              _this.deleteDate(scope["row"].id);
            },
          },
        },
      },
    };
  },
  methods: {


    chapterChange: function (val) {
      _this.rule[1].options.map((item) => {
        if (item.id === val) {
          return _this.fapi.setValue('chapter_name', item.title);
        }
      })
    },

    userFilterMethod: function (val) {
      _this.getUserList(1, val)
    },
    classChange: function (val) {
      _this.getChapterList(1, '', val);
      _this.fapi.setValue('chapter_id', '');
    },

    classClear: function () {
      _this.getClassList();
    },

    chapterClear: function () {
      _this.getChapterList(1, '', _this.fapi.getValue('class_id'));
    },
    userClear: function () {
      _this.getUserList();
    },

    classCurrentChange: function (val) {
      _this.getClassList(val);
    },
    chapterCurrentChange: function (val) {
      _this.getChapterList(val);
    },
    userCurrentChange: function (val) {
      _this.getUserList(val);
    },
    chapterFilterMethod: function (val) {
      _this.getChapterList(val);
    },

    classFilterMethod: function (val) {
      _this.getClassList(1, val);
    },

    handlePaginationCurrentChange: function (val) {
      _this.loading = true;
      _this.pagination["currentPage"] = val;
      _this.getDateList();
    },

    handlePaginationSizeChange: function (val) {
      _this.loading = true;
      _this.pagination["pageSize"] = val;
      _this.getDateList();
    },

    /**
     * 查询所有专业数据
     */
    getDateList: function () {
      _this.$store
        .dispatch("office/getStudyRecordList", {
          page: _this.pagination["currentPage"],
          pageSize: _this.pagination["pageSize"],
        })
        .then(() => {
          _this.loading = false;
          _this.dialogVisible = false;
          let data = this.$store.state.office.studyRecordList;
          this.tableData = data.data;
          _this.pagination["currentPage"] = data["current_page"];
          _this.pagination["total"] = data["total"];
        });
    },

    /**
     * 查询课程数据
     */
    getClassList: function (page = 1, title) {
      _this.$store
        .dispatch("office/getClassSelectList", {
          page: page,
          title: title,
        })
        .then((res) => {
          _this.rule[0].options.length = 0;
          res.data.data.forEach((item) => {
            let obj = {
              id: item.id,
              title: item.title,
              garde: item.garde,
              class_code: item.class_code,
            }
            _this.rule[0].options.push(obj);
          })
          _this.pageSizes.classPage.currentPage = res.data.current_page;
          _this.pageSizes.classPage.total = res.data.total;

        });
    },

    /**
     * 查询章节数据
     */
    getChapterList: function (page = 1, title, class_id) {
      _this.$store
        .dispatch("office/getChapterSelectList", {
          page: page,
          title: title,
          class_id: class_id
        })
        .then((res) => {
          _this.rule[1].options = [];
          res.data.data.forEach((item) => {
            let obj = {
              id: item.id,
              title: item.title,
            }
            _this.rule[1].options.push(obj);
          })
          _this.pageSizes.chapterPage.currentPage = res.data.current_page;
          _this.pageSizes.chapterPage.total = res.data.total;

        });
    },


    /**
     * 查询用户信息
     */
    getUserList: function (page = 1, name) {
      _this.$store
        .dispatch("office/getUserList", {
          page: page,
          name: name,
        })
        .then((res) => {
          console.log(res)
          _this.rule[2].options = [];
          res.data.data.forEach((item) => {
            let obj = {
              id: item.id,
              name: item.name,
              idcard: item.idcard == null ? '' : item.idcard.substring(item.idcard.length - 4)
            }
            _this.rule[2].options.push(obj);
          })
          _this.pageSizes.userPage.currentPage = res.data.current_page;
          _this.pageSizes.userPage.total = res.data.total;
        });
    },

    /**
     * 批量删除
     */
    handleHeardDel: function (val) {
      let del = [];
      val.forEach((item, index) => {
        del.push(item.id);
      });
      _this.deleteDate(del);
    },


    addDate: function (param) {
      _this.$store
        .dispatch("office/addStudyRecord", {
          class_id: param["class_id"],
          chapter_id: param["chapter_id"],
          user_id: param["user_id"],
          chapter_name: param["chapter_name"],
          is_pass: param["is_pass"],
          play_time: param["play_time"],
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.$message.success(msg);
            _this.getDateList();
          } else {
            _this.$message.error(msg);
          }
        });
    },
    /**
     * 表单提交回调
     */
    onSubmit: function (val) {
      if (_this.alertTitle === "添加") {
        _this.addDate(val);
      } else {
        _this.updateDate(val);
      }
    },

    resetForm:function (){},
    /**
     * 搜索角色标题
     */
    searchForm: function (val) {

    },
    /**
     * 更新角色
     */
    updateDate: function (param) {
      _this.$store
        .dispatch("office/updateStudyRecord", {
          id: _this.row["id"],
          class_id: param["class_id"],
          chapter_id: param["chapter_id"],
          user_id: param["user_id"],
          chapter_name: param["chapter_name"],
          is_pass: param["is_pass"],
          play_time: param["play_time"],
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.getDateList();
            _this.$message.success(msg);
            return;
          }
          return _this.$message.error(msg);
        });
    },

    /**
     * 删除角色
     */
    deleteDate: function (val) {
      _this.$store
        .dispatch("office/deleteStudyRecord", {
          id: val,
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.getDateList();
            _this.$message.success(msg);
            return;
          }
          return _this.$message.error(msg);
        });
    },

    /**
     *  表单导航栏添加点击
     */
    handleAdd: function () {
      _this.alertTitle = "添加";
      this.dialogVisible = true;
    },
  },
  watch: {
    dialogVisible(newVal) {
      setTimeout(() => {
        if (!newVal) {
          _this.fapi.resetFields(); //清空数据
          _this.fapi.setValue('content', '');
        }
      }, 0);
    },
  },
  created() {
    _this = this;
  },
  mounted() {
    this.getDateList();
    this.getClassList();
    this.getUserList();
  },
};
</script>

<style scoped></style>
